package com.hushui.mall.order.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.hushui.common.exception.NoStockException;
import com.hushui.common.to.MemberResponseVo;
import com.hushui.common.utils.PageUtils;
import com.hushui.common.utils.R;
import com.hushui.mall.order.config.AlipayTemplate;
import com.hushui.mall.order.service.OrderService;
import com.hushui.mall.order.vo.OrderConfirmVo;
import com.hushui.mall.order.vo.OrderSubmitVo;
import com.hushui.mall.order.vo.PayVo;
import com.hushui.mall.order.vo.SubmitOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import static com.hushui.common.utils.Constant.AuthServerConstant.LOGIN_USER;

/**
 * @Author: hwh
 * @Date: 2023/03/16/11:22
 */
@Slf4j
@RequestMapping("order")
@Controller
public class OrderWebController {
    @Autowired
    OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;

    @GetMapping("getFare")
    public R getFare(@RequestParam Long addrId) {
        return orderService.getFare(addrId);

    }


    /**
     * 跳转到我的订单
     *
     * @param
     * @param model
     * @return
     */
    @GetMapping("orderList.html")
    public String memberOrderPage(@RequestParam(value = "pageNum",required = false,defaultValue = "0") Integer pageNum,
                                  Model model) {

        //获取到支付宝给我们转来的所有请求数据
        //request,验证签名

        //查出当前登录用户的所有订单列表数据
        Map<String,Object> page = new HashMap<>();
        page.put("page",pageNum.toString());
        PageUtils pageUtils = orderService.queryPageWithItem(page);
        log.info(pageUtils.toString());
        //查询订单服务订单数据
        model.addAttribute("orders",R.ok().put("page", pageUtils));

        return "list";
    }


    /**
     * 跳转到确认订单界面
     *
     * @param params
     * @param model
     * @return
     */
    @GetMapping("confirm.html")
    public String toConfirm(@RequestParam Map<String, Object> params, Model model) throws ExecutionException, InterruptedException {

        OrderConfirmVo confirmVo = orderService.confirmOrder(params);
        model.addAttribute("confirmOrderData", confirmVo);
        return "confirm";
    }

    /**
     * 跳转到支付界面
     *
     * @param orderSn
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/aliPayOrder", produces = "text/html")
    public String toPay(@RequestParam("orderSn") String orderSn) throws AlipayApiException {

        PayVo payVo = orderService.getOrderPay(orderSn);
        String pay = alipayTemplate.pay(payVo);
        System.out.println(pay);
        return pay;
    }

    /**
     * 跳转到等待付款界面
     *
     * @param params
     * @param model
     * @return
     */
    @GetMapping("detail.html")
    public String toDetails(@RequestParam Map<String, Object> params, Model model) {

        model.addAttribute("aa", orderService.queryPage(params));
        return "detail";
    }

    /**
     * 确认，提交订单
     *
     * @param submitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(HttpSession session, OrderSubmitVo submitVo, Model model, RedirectAttributes redirectAttributes) {
        try {
            System.out.println(session.getAttribute(LOGIN_USER).toString());
            MemberResponseVo member = (MemberResponseVo) session.getAttribute(LOGIN_USER);
            System.out.println(member);
            SubmitOrderResponseVo responseVo = orderService.submitOrder(submitVo);
            //创建订单，验证令牌，验价格，所库存
            // 成功。。跳转到支付界面
            //失败。。回到订单确认页，重新确认订单信息
            System.out.println("订单提交的数据...+" + responseVo);
            if (responseVo.getCode() == 0) {
                //成功
                model.addAttribute("submitOrderResp", responseVo);
                return "pay";
            } else {
                String msg = "下单失败";
                switch (responseVo.getCode()) {
                    case 1:
                        msg += "订单信息，请刷新后再次提交";
                        break;
                    case 2:
                        msg += "订单价格发生变化，请确认后再次提交！";
                        break;
                    case 3:
                        msg += "库存锁定失败，商品库存不足";
                        break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://localhost:8008/order/confirm.html";
            }
        } catch (Exception e) {
            if (e instanceof NoStockException) {
                String message = ((NoStockException) e).getMessage();
                redirectAttributes.addFlashAttribute("msg", message);
            }
            return "redirect:http://localhost:8008/order/confirm.html";
        }
    }


}
